package com.test.netty.websocket;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 接收事件-用于处理channel超时事件
 */
@Slf4j
@ChannelHandler.Sharable
public class AcceptorIdleStateTrigger extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            //channel读取超时事件
            //这里的超时不是指读取数据超时，而是指客户端在规定时间内没有发送数据给服务器端
            if (state == IdleState.READER_IDLE) {
                log.debug("Read Idel =>> " + state + " client =>>" + ctx.channel().remoteAddress());
                throw new Exception("idle exception");
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.warn("exceptionCaught =>> " + cause.getMessage() + " client =>> " + ctx.channel().id().asLongText());
        cause.printStackTrace();
        ctx.close();
    }
}
